<?php
declare (strict_types = 1);

namespace app\api\controller;
use app\BaseController;

use app\common\model\UserfilesModel;
use think\facade\Db;
use think\facade\Session;
use think\facade\Config;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;

    /**
	 * Created by Ailcc.com
     * 2021-11-14 12:00:00 沛霖主页
     * 
	 */
class Uploads extends BaseController
{
    public function edit(){
        $admin_id = Session::get('admin_id');
        if(empty($admin_id)){
            return json(['code'=>1, 'msg'=>'请先登录','data'=>[]]);
        }
        
        // 获取表单上传文
        $file = request()->file('file');
        
        try {
            validate(['file' => [
                'fileSize' => 41943040,  //5M
            ]])->check(['file' => $file]);
	        $savename = \think\facade\Filesystem::disk('storage')->putFile( 'file', $file);
            //上传到本地服务器
            if (!$savename) {
                // return json(['code'=>1, 'msg'=>'上传失败，不支持的格式']);
            }else{
	            $fullname = $this->request->scheme().'://'.$this->request->host().'/storage/'.$savename;
                $data['src'] = $fullname;
                $data['title'] = '图片';
	            return json(['code'=>0, 'msg'=>'上传成功', 'data'=>$data]);
            }
        }catch (\Exception $e) {
            return json(['code' => 1,'msg'=>'上传失败，不支持的格式',]);
        }
    }
    
    //广告上传 限制广告图大小为500kb 限制图片类型
    //相册上传 生成省略图
    public function photos(){
        $admin_id = Session::get('admin_id');
        if(empty($admin_id)){
            return json(['code'=>1, 'msg'=>'请先登录','data'=>[]]);
        }
        $config = Db::name('setting')->where('group','zh')->column('value','name');
	    $file = request()->file('file');
	    $column = input('column','pool');
	   // 上传到七牛云
	    $img_type = $file->getOriginalExtension();
	    try {
            validate(['file' => [
                'fileSize' => 41943040,  //5M
                'fileExt' => 'jpg,png,gif,jpeg',
                'fileMime' => 'image/jpeg,image/png,image/gif',
            ]])->check(['file' => $file]);
            
            $key=input('post.text');    // 获取表单上传文件
            $image = request()->file('file');    //获取上传后的文件路径
            $filePath = $image->getRealPath();    // 图片存储在本地的临时路经
            $ext = $image->getOriginalExtension();    // 获取图片后缀
            $newImageName = 'storage/'.$column.'/'.date('Y/m/d/').substr(md5($image->getOriginalName()),0,12).rand(00000,99999).'.'.$ext;    // 上传到七牛后保存的图片名及文件地址
            $auth = new Auth($config['qiniu_AccessKey'],$config['qiniu_SecretKey']);
            $token = $auth->uploadToken($config['qiniu_bucket']);    // 要上传的空间位置
            $uploadMgr = new UploadManager();    // 初始化 UploadManager 对象并进行文件的上传。
            list($ret , $err) = $uploadMgr->putFile($token , $newImageName , $filePath);
            if($err !== null){
                return json(['code'=>1, 'msg'=>'上传失败，出现未知错误']);
            }else{
                // 图片上传成功
                $data['src'] = $config['qiniu_url'].$newImageName; //返回图片地址
    	        $data['path'] = $filePath;    //返回省略图地址
    	        $data['fullpath'] = $newImageName;
    	        $data['title'] = $image->getOriginalName();
    	        $data['type'] = $ext;
            	$data['img_type'] = $image->getOriginalMime();
            	$data['size'] = round($image->getSize()/(1024*1024),3).'M';
                return json(['code'=>0, 'msg'=>'上传成功', 'data'=>$data]);
            }
        }catch (\Exception $e) {
            return json(['code' => 1,'msg'=>'上传失败，不支持的格式',]);
        }
	    
	    
        // try {
        //     validate(['file' => [
        //         'fileSize' => 41943040,  //5M
        //         'fileExt' => 'jpg,png,gif,jpeg',
        //         'fileMime' => 'image/jpeg,image/png,image/gif',
        //     ]])->check(['file' => $file]);
	       //// $savename = \think\facade\Filesystem::disk('public')->putFile( $column, $file);
	       // $savename =  \think\facade\Filesystem::disk('qiniu')->putFile($column,$file);
        //     //上传到本地服务器
        //     if (!$savename) {
        //         // return json(['code'=>1, 'msg'=>'上传失败，不支持的格式']);
        //     }else{
	       //     $path = env('filesystem.storage','/storage').'/'.str_replace("\\","/",$savename);       //上传地址
	       //     $fullpath = $this->request->scheme().'://'.$this->request->host().$path;
        //         $images = './storage/'.$column.'/'.date('Ymd').'/'.time().'-1.'.$img_type;   //存储省略图地址
	       //     $urlimg = str_replace("./","/",$images);
	       //     $image = \think\Image::open(request()->file('file'));       //打开图片
        //         $image->thumb(366, 306,\think\Image::THUMB_CENTER)->save($images);      //生成sheng
	       //     $data['src'] = $path; //返回图片地址
	       //     $data['path'] = $urlimg;    //返回省略图地址
	       //     $data['fullpath'] = $fullpath;
	       //     $data['title'] = $file->getOriginalName();
	       //    // $data['type'] = $file->getOriginalExtension();
        // 	   // $data['img_type'] = $file->getOriginalMime();
        // 	   // $data['size'] = round($file->getSize()/(1024*1024),3).'M';
        // 	   // UserfilesModel::add($path);
	       //     return json(['code'=>0, 'msg'=>'上传成功', 'data'=>$data]);
        //     }
        // }catch (\Exception $e) {
        //     return json(['code' => 1,'msg'=>'上传失败，不支持的格式',]);
        // }
    }

    public function delnews_test(){
        $admin_id = Session::get('admin_id');
        if(empty($admin_id)){
            return json(['code'=>1, 'msg'=>'请先登录','data'=>[]]);
        }
        
        $path = $this->request->param('imgpath');
        unlink(".".$path);
        PhotosModel::destroy($id);
        return json(['code'=>0,'msg'=>'删除成功']);
    }


}
